import React from 'react';
import { Button, View, Image, Alert, PermissionsAndroid, Platform } from 'react-native';
import ImagePicker from 'react-native-image-picker';
 
const App = () => {
  const [image, setImage] = React.useState(null);
 
  const pickImage = () => {
    if (Platform.OS === 'android') {
      //动态获取权限
      PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: '需要存储权限',
          message: '需要访问您的存储以保存图片',
          buttonNeutral: '稍后',
          buttonNegative: '取消',
          buttonPositive: '确定',
        },
      )
       .then(granted => {
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log('权限申请成功');
          } else {
            console.log('权限申请失败');
          }
        })
       .catch(err => {
          console.log('权限申请失败', err);
        });
    }
    const options = {
      title: '选择图片',
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };
    ImagePicker.launchCamera(options, response => {
      if (response.didCancel) {
        console.log('用户取消了图片选择');
      } else if (response.error) {
        console.log('选择图片时发生错误: ', response.error);
        Alert.alert('选择图片时发生错误', response.error);
      } else {
        setImage(response.uri);
      }
    });
  };
 
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="选择图片" onPress={pickImage} />
      {image && <Image source={image} style={{ width: 200, height: 200 }} />}
    </View>
  );
};
 
export default App;